package com.wlw.admin.openeye.mvp.presenter

import android.app.Activity
import com.wlw.admin.openeye.MyApplication
import com.wlw.admin.openeye.base.BasePresenter
import com.wlw.admin.openeye.dataFormat
import com.wlw.admin.openeye.mvp.contract.VideoDetailContract
import com.wlw.admin.openeye.mvp.model.VideoDetailModel
import com.wlw.admin.openeye.mvp.model.bean.HomeBean
import com.wlw.admin.openeye.net.exception.ExceptionHandle
import com.wlw.admin.openeye.showToast
import com.wlw.admin.openeye.utils.DisplayManager
import com.wlw.admin.openeye.utils.NetworkUtil

class VideoDetailPresenter : BasePresenter<VideoDetailContract.View>(), VideoDetailContract.Presenter {

    private val videoDetailModel by lazy {
        VideoDetailModel()
    }


    override fun loadVideoInfo(itemInfo: HomeBean.Issue.Item) {
        val playInfo = itemInfo.data?.playInfo
        val netType = NetworkUtil.isWifi(MyApplication.context)
        checkViewAttached()
        if (playInfo!!.size > 1) {
            if (netType) {
                for (i in playInfo) {
                    if (i.type == "high") {
                        val playUrl = i.url
                        mRootView?.setVideo(playUrl)
                        break
                    }
                }
            } else {
                for (i in playInfo) {
                    if (i.type == "normal") {
                        val playUrl = i.url
                        mRootView?.setVideo(playUrl)
                        (mRootView as Activity).showToast("本次消耗${dataFormat(i.urlList[0].size)}流量")
                        break
                    }
                }
            }
        } else {
            mRootView?.setVideo(itemInfo.data.playUrl)
        }
        val backgroundUrl = itemInfo.data.cover.blurred + "/thumbnail/${DisplayManager.getScreenHeight()!! - DisplayManager.dip2px(250f)!!}x${DisplayManager.getScreenWidth()}"
        backgroundUrl.let {
            mRootView?.setBackground(it)
        }
        mRootView?.setVideoInfo(itemInfo)
    }

    override fun requestRelatedVideo(id: Long) {
        mRootView?.showLoading()
        val disposable = videoDetailModel.requestRelatedData(id).subscribe({
            mRootView?.apply {
                dismissLoading()
                setRecentRelatedVideo(it.itemList)
            }
        }, { t ->
            mRootView?.apply {
                dismissLoading()
                setError(ExceptionHandle.handleException(t))
            }
        })
        addSubscription(disposable)
    }
}